import { deleteRecent, changeRemarks, contactMessageDelete, contactMessageDeleteAll } from '../../api/contact'
import { deleteRecentGroup, groupUpdate, groupMemberExit, groupDissolution, groupMessageDelete, groupMessageDeleteAll } from '../../api/group'
import tools from '../../utils/tools'

const state = {
  // 聊天列表+聊天内容
  chatInformation: [
  ],
  // 所有已操作用户的信息列表
  userList: {
    temp: 0
  },
  // 所有已操作群组的信息列表
  groupList: {
    temp: 0
  },
  // 当前正在聊天的用户/群组
  current_contact: {},
  // 系统通知
  systemNotiList: [ // 留着后续不同的提醒
    { id: 'notification', name: '消息通知', messages: [], timestamp: +new Date(), id_type: 0 }
  ],
  // 被删除消息id
  deleteMsgID: null
}

const getters = {
  // 未读消息总和
  unreadMsgCount (state) {
    let count = 0
    state.chatInformation.forEach(item => {
      item.messages.forEach(it => {
        if (it.unread) {
          count++
        }
      })
    })
    return count
  }
}

const mutations = {
  // 设置当前正在聊天的联系人/群组
  set_current_contact (state, contact) {
    state.current_contact = contact
    if (contact.id_type === 1) {
      state.userList.temp++
    } else {
      state.groupList.temp++
    }
  },
  // 替换聊天联系人列表
  replace_contact (state, list) {
    const newList = list.filter(item => item.name)
    newList.unshift(state.systemNotiList[0])
    state.chatInformation = newList
  },
  // 置顶某联系人
  set_topContact (state, contact) {
    if (state.chatInformation.some(item => item.id_type === contact.id_type && item.id === contact.id)) {
      const topUser = state.chatInformation.filter(item => item.id_type === contact.id_type && item.id === contact.id)
      const others = state.chatInformation.filter(item => !(item.id_type === contact.id_type && item.id === contact.id))
      state.chatInformation = [...topUser, ...others]
    } else {
      state.chatInformation.unshift(contact)
    }
  },
  // 将联系人身份变更
  reset_identify (state, { id, bool }) {
    state.chatInformation.forEach(item => {
      if (item.id === id && item.id_type === 1) {
        item.in_contact = bool
      }
    })
    state.userList[id].in_contact = bool
    state.userList = JSON.parse(JSON.stringify(state.userList))
  },
  // 将联系人备注变更
  set_remarks (state, { id, remarks }) {
    state.userList[id].remarks = remarks
    state.userList = JSON.parse(JSON.stringify(state.userList))
    state.chatInformation.forEach(item => {
      if (item.id === id && item.id_type === 1) {
        item.remarks = remarks
      }
    })
    state.chatInformation = state.chatInformation.filter(item => item)
  },
  // 修改群组名称
  update_groupName (state, { id, name }) {
    state.groupList[id].group_name = name
    state.groupList = JSON.parse(JSON.stringify(state.groupList))
    state.chatInformation.forEach(item => {
      if (item.id === id && item.id_type === 2) {
        item.name = name
      }
    })
    state.chatInformation = state.chatInformation.filter(item => item)
  },
  // 修改群主
  update_sponsor (state, { groupID, userID }) {
    state.groupList[groupID].group_sponsor = userID
    state.groupList = JSON.parse(JSON.stringify(state.groupList))
  },
  // 删除某联系人的聊天
  remove_contact (state, { id, idType }) {
    state.chatInformation = state.chatInformation.filter(item => !(item.id === id && item.id_type === idType))
  },
  // 添加一条聊天消息
  add_Message (state, { message, id, idType, ifFront }) {
    state.chatInformation.forEach((item) => {
      if (item.id === id && item.id_type === idType) {
        if (ifFront) {
          if (item.messages.every(msg => msg.msg_id !== message.msg_id)) {
            item.messages.unshift(message)
          }
        } else {
          item.messages.push(message)
        }
        // 新增标志位 控制是否置底
        item.ifBottom = !ifFront
        item.messages.filter(it => it)
      }
    })
  },
  // 给当前发出的消息补充msgID和清空reqID
  supplement_msgId (state, { id, idType, msgID }) {
    state.chatInformation.forEach(item => {
      if (item.id === id && item.id_type === idType) {
        item.messages[item.messages.length - 1].msg_id = msgID
        item.messages.forEach(msg => {
          if (msg.reqId) {
            msg.reqId = null
          }
        })
        item.messages = item.messages.filter(item => item)
      }
    })
  },
  // 撤回某联系人某条消息
  withdrawMsg (state, msgInfo) {
    state.chatInformation.forEach(item => {
      if (item.id === msgInfo.id && item.id_type === msgInfo.id_type) {
        item.messages.forEach(msg => {
          if (msg.msg_id === msgInfo.msg_id) {
            const timestamp = msg.timestamp
            for (const key in msg) {
              delete msg[key]
            }
            msg.special = true
            msg.type = 'withdraw'
            msg.timestamp = timestamp
            msg.withdrawer = msgInfo.id
            msg.isSelf = msgInfo.isSelf
          }
        })
        item.messages = item.messages.filter(it => it)
      }
    })
  },
  // 设置被删除消息ID
  set_deleteMsgID (state, msgID) {
    state.deleteMsgID = msgID
  },
  // 删除某联系人指定消息
  delete_msg (state, { id, idType, messageID }) {
    state.chatInformation.forEach(item => {
      if (item.id === id && item.id_type === idType) {
        // 查找当前被删除消息的index
        const deleteMsgIndex = item.messages.findIndex(msg => msg.msg_id === messageID)
        // 如果被删除消息的前一项为时间消息
        if (item.messages[deleteMsgIndex - 1] && item.messages[deleteMsgIndex - 1].special && item.messages[deleteMsgIndex - 1].type === 'time') {
          // 如果被删除消息的后一项不为特殊消息，则让前一项的时间消息的时间替换为后一项的时间
          if (item.messages[deleteMsgIndex + 1] && !item.messages[deleteMsgIndex + 1].special) {
            item.messages[deleteMsgIndex - 1].timestamp = item.messages[deleteMsgIndex + 1].timestamp
            item.messages[deleteMsgIndex - 1].msg_id = item.messages[deleteMsgIndex + 1].timestamp
          } else {
            // 如果后一项不存在或者为特殊消息，则删除前一项的时间消息
            item.messages = item.messages.filter(msg => msg.msg_id !== item.messages[deleteMsgIndex - 1].msg_id)
          }
        }
        // 如果被删除消息的前一项不为时间消息，则不用进行处理，直接删除被删除消息
        item.messages = item.messages.filter(msg => msg.msg_id !== messageID)
      }
    })
  },
  // 删除某联系人所有消息
  delete_messages (state, { id, idType }) {
    state.chatInformation = state.chatInformation.map(item => {
      if (item.id === id && item.id_type === idType) {
        item.messages = []
      }
      return item
    })
  },
  // 为指定联系人添加草稿
  set_draft (state, { id, idType, draft }) {
    state.chatInformation.forEach(item => {
      if (item.id === id && item.id_type === idType) {
        item.draft = draft
      }
    })
    state.chatInformation = state.chatInformation.filter(item => item)
  },
  // 添加一条已操作的用户信息至用户信息列表中
  add_user (state, { userID, userInfo }) {
    if (!Object.keys(state.userList).some(item => item === userID)) {
      state.userList[userID] = userInfo
      state.userList.temp++
    }
  },
  // 给现存在用户信息列表中的用户补充头像数据
  supplement_user_img (state, { userID, userImg, userImgID }) {
    state.userList[userID].user_img = userImg
    state.userList[userID].user_img_id = userImgID
    state.userList = JSON.parse(JSON.stringify(state.userList))
    state.userList.temp++
  },
  // 给现存在群组信息列表中的群组补充/修改头像数据
  supplement_group_img (state, { groupID, groupImg, groupImgID }) {
    state.groupList[groupID].group_img = groupImg
    state.groupList[groupID].group_img_id = groupImgID
    state.groupList = JSON.parse(JSON.stringify(state.groupList))
    state.groupList.temp++
  },
  // 清除创建群聊的标识位
  clear_newCreate (state, groupID) {
    delete state.groupList[groupID].newCreate
  },
  // 编辑当前用户是否已经被移出某群聊
  set_group_ifKickedOut (state, groupID) {
    state.chatInformation.forEach(item => {
      if (item.id === groupID && item.id_type === 2) {
        item.ifKickedOut = true
      }
    })
    state.chatInformation = state.chatInformation.filter(item => item)
  },
  // 编辑当前群聊是否已被解散
  set_group_dissolution (state, groupID) {
    state.chatInformation.forEach(item => {
      if (item.id === groupID && item.id_type === 2) {
        item.ifDissolution = true
      }
    })
    state.chatInformation = state.chatInformation.filter(item => item)
  },
  // 添加一条已操作的群组信息至用户信息列表中
  add_group (state, { groupID, groupInfo }) {
    if (!Object.keys(state.groupList).some(item => item === groupID)) {
      state.groupList[groupID] = groupInfo
      state.groupList.temp++
    }
  },
  // 使某联系人的未读消息清空
  clear_unreadMessage (state, { id, idType }) {
    state.chatInformation.forEach(item => {
      if (item.id === id && item.id_type === idType) {
        item.messages.forEach(item => {
          if (item.unread) {
            item.unread = false
          }
        })
      }
    })
    state.chatInformation = state.chatInformation.filter(item => item)
  },
  // 使某用户某语音消息变为已听
  set_userMessage_listened (state, { id, idType, msgID }) {
    state.chatInformation.forEach(item => {
      if (item.id === id && item.id_type === idType) {
        item.messages.forEach(it => {
          if (it.msg_id === msgID) {
            it.listened = true
          }
        })
      }
    })
    state.chatInformation = state.chatInformation.filter(item => item)
  }
}

const actions = {
  // 添加一条新消息
  setAddMessage ({ commit, rootState }, { message, id, idType, ifFront }) {
    if (ifFront) {
      commit('add_Message', { message, id, idType, ifFront })
      // 判断是否显示消息时间
      tools.time.createTimeMessage(id, idType, message, ifFront)
    } else {
      // 发消息时，将req_id关联当前消息对象
      message.reqId = rootState.socket.operationReqId.sendMessageId
      // 判断是否显示消息时间
      tools.time.createTimeMessage(id, idType, message, ifFront)
      commit('add_Message', { message, id, idType, ifFront })
    }
  },
  // 移除最近联系人
  removeRecent ({ state, commit }, userInfo) {
    return new Promise((resolve, reject) => {
      const { id, idType } = userInfo
      if (idType === 1) {
        // 私聊
        deleteRecent(id).then(res => {
          if (res.data && res.data.code === 200) {
            commit('remove_contact', { id, idType })
            if (state.current_contact.id === id && state.current_contact.id_type === idType) {
              commit('set_current_contact', {})
            }
          }
          resolve(res)
        }).catch(err => {
          reject(err)
        })
      } else {
        // 群聊
        deleteRecentGroup(id).then(res => {
          if (res.data && res.data.code === 200) {
            commit('remove_contact', { id, idType })
            if (state.current_contact.id === id && state.current_contact.id_type === idType) {
              commit('set_current_contact', {})
            }
          }
          resolve(res)
        }).catch(err => {
          reject(err)
        })
      }
    })
  },
  // 设置备注
  editRemark ({ commit, dispatch, rootState }, { id, remarks }) {
    return new Promise((resolve, reject) => {
      changeRemarks(id, remarks).then(res => {
        console.log(res)
        if (res.data.code === 200) {
          commit('set_remarks', { id, remarks })
          // 判断当前联系人是否为群组，为群组则将当前群组用户列表更新
          if (rootState.chatInformation.current_contact.id_type === 2) {
            dispatch('groups/getGroupMemberList', rootState.chatInformation.current_contact.id, { root: true })
          }
          resolve(res)
        }
      })
    })
  },
  // 修改群聊名称
  updateGroupName ({ commit }, { groupID, groupName }) {
    return new Promise((resolve, reject) => {
      groupUpdate(groupID, groupName).then(res => {
        resolve(res)
      }).catch(err => {
        reject(err)
      })
    })
  },
  // 退出群聊
  exitGroup (context, groupID) {
    return new Promise((resolve, reject) => {
      groupMemberExit(groupID).then(res => {
        resolve(res)
      }).catch(err => {
        reject(err)
      })
    })
  },
  // 解散群聊
  dissolutionGroup (context, groupID) {
    return new Promise((resolve, reject) => {
      groupDissolution(groupID).then(res => {
        resolve(res)
      }).catch(err => {
        reject(err)
      })
    })
  },
  // 删除私聊指定消息
  deleteUserMessage ({ commit }, { targetID, messageIDS }) {
    return new Promise((resolve, reject) => {
      contactMessageDelete(targetID, messageIDS).then(res => {
        if (res.data && res.data.code === 200) {
          commit('delete_msg', { id: targetID, idType: 1, messageID: messageIDS[0] })
        }
        resolve(res)
      }).catch(err => {
        reject(err)
      })
    })
  },
  // 删除聊天记录-私聊
  deleteUserAllMessage ({ commit }, userID) {
    return new Promise((resolve, reject) => {
      contactMessageDeleteAll(userID).then(res => {
        if (res.data && res.data.code === 200) {
          commit('delete_messages', { id: userID, idType: 1 })
        }
        resolve(res)
      }).catch(err => {
        reject(err)
      })
    })
  },
  // 删除群聊指定消息
  deleteGroupMessage ({ commit }, { groupID, groupMessages }) {
    return new Promise((resolve, reject) => {
      groupMessageDelete(groupID, groupMessages).then(res => {
        if (res.data && res.data.code === 200) {
          commit('delete_msg', { id: groupID, idType: 2, messageID: groupMessages[0] })
        }
        resolve(res)
      }).catch(err => {
        reject(err)
      })
    })
  },
  // 删除聊天记录-群聊
  deleteGroupAllMessage ({ commit }, groupID) {
    return new Promise((resolve, reject) => {
      groupMessageDeleteAll(groupID).then(res => {
        if (res.data && res.data.code === 200) {
          commit('delete_messages', { id: groupID, idType: 2 })
        }
        resolve(res)
      }).catch(err => {
        reject(err)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}
